<script setup>
import { ref, onMounted } from 'vue'
import { throttle, calculateStartPosition, calculateNewPosition, sessionParam } from '@/utils'
import { getAppInfo } from '@/api/webphone'

const position = ref({ x: 510, y: 30 })
const isDragging = ref(false)
const startPosition = ref({ x: 0, y: 0 })

const startDrag = (e) => {
  isDragging.value = true
  startPosition.value = calculateStartPosition(e, position.value)

  window.addEventListener('mousemove', onDrag)
  window.addEventListener('mouseup', stopDrag)
}

const updatePosition = (e) => {
  if (isDragging.value) {
    position.value = calculateNewPosition(e, startPosition.value)
  }
}

const onDrag = throttle(updatePosition, 16)

const stopDrag = () => {
  isDragging.value = false
  window.removeEventListener('mousemove', onDrag)
  window.removeEventListener('mouseup', stopDrag)
}
const app = ref({});
onMounted(async () => {
  await GetAppInfo();
  initPhone()
})

const GetAppInfo = async () => {
  const res = await getAppInfo();
  app.value = res;
  return res
}

const initPhone = async () => {
  const param = {
    ...sessionParam,
    userInfo: {
      authCode: app.value.authCode,
    },
    appInfo: {
      appId: app.value.persistentAppInstanceId,
      loginRegionId: app.value.regionId,
    },
  };

  const wuyingSdk = Wuying.WebSDK;
  const session = wuyingSdk.createSession('appstream', param);
  session.addHandle('getConnectionTicketInfo', (data) => {
    console.log('获取手机连接信息', data);
  });

  session.addHandle('onConnected', (data) => {
    console.log('云手机连接成功', data);
    // 监听数据通道消息
    session.addDataChannelListener('wy_vdagent_default_dc', 'data', data => console.log('data from wy_vdagent_default_dc', data));

    // 发送数据通道消息消息
    // 入参： 通道名称  消息内容
    setTimeout(() => {
      session.sendDataChannelMessage('wy_vdagent_default_dc', new Uint8Array([1, 2, 3, 4]));
    }, 5000)
  });

  session.addHandle('onDisConnected', (data) => {
    console.log('云手机断开连接', data);
  });

  session.addHandle('onRuntimeMsg', (data) => {
    console.log('云手机运行时消息', data);
  });

  session.start();
}

</script>
<template>
  <div class="web-phone need-zoom" :style="{ transform: `translate(${position.x}px, ${position.y}px)` }">
    <div class="set-top" @mousedown="startDrag"></div>
    <iframe id="sessionIframe" class="iframe-container"></iframe>
    <div :class="`cover ${isDragging}`"></div>
  </div>
</template>

<style>
.web-phone {
  z-index: 520;
  position: absolute;
  width: 432px;
  height: 798px;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  .set-top{
    height: 30px;
    background-color: #ddd;
    cursor: move;
  }
  .iframe-container {
    width: 432px;
    height: 768px;
    line-height: 0px;
    border: none;
    background-color: #47406e;
  }
  .cover.true{
    position: absolute;
    top: 29px;
    left: 0;
    width: 100%;
    height: 100%;
  }
}

</style>
